package com.bibi.zoo.demo;

import com.baidu.aip.ocr.AipOcr;
import com.bibi.zoo.pkg.req.ReqLogin;
import com.bibi.zoo.pkg.resp.BaseResp;
import com.bibi.zoo.pkg.resp.RespLogin;
import com.bibi.zoo.pkg.resp.RespVerifyCode;
import org.json.JSONObject;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class TestDemo {
    static RestTemplate restTemplate = new RestTemplateBuilder().build();
    static int aid = 1;
    public static void main(String[] args) {
        RespVerifyCode respVerifyCode;
        Integer code;
        while(true) {
            //获取验证码
            respVerifyCode = getCodeUrl();
            if(respVerifyCode == null) {
                continue;
            }
            //识别验证码
            code = getCode(respVerifyCode.getData().getUrl());
            if(code != null) {
                break;
            }
        }
        System.out.println(code);
        //登录
       /* RespLogin loginRes = login(respVerifyCode, code);
        String luckkey = loginRes.getData();
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        authHeaders.add("luckkey",luckkey);
        authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //获取个人信息
        HttpEntity<String> requestEntity = new HttpEntity<>(null, authHeaders);
        RespUserInfo respUserInfo = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/assets/findUserAssetsByUser", requestEntity, RespUserInfo.class);
        System.out.println("用户信息：" + com.alibaba.fastjson.JSONObject.toJSONString(respUserInfo));
        //获取生肖列表
        //整理秒杀账号列表
        //账号实名检测
        //预约
        boolean invite = invite(authHeaders);
        //抢购  并行查询开奖结果
        if(invite) {
            flushBuy(authHeaders);
        }*/
    }

    private static void flushBuy(HttpHeaders authHeaders) {
        new Thread(() -> {
            while (true) {
                HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                Map<String,Object> params = new HashMap<>();
                params.put("id",aid);
                BaseResp baseResp = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/game/flash_buy/{id}", requestEntity2, BaseResp.class,params);
                System.out.println("抢购结果：" + com.alibaba.fastjson.JSONObject.toJSONString(baseResp));
            }
        }).start();
        new Thread(() -> {
            while (true) {
                HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                Map<String,Object> params = new HashMap<>();
                params.put("id",aid);
                ResponseEntity<BaseResp> exchange = restTemplate.exchange("http://luck9.luckyzodiac12.com/api/game/checkOpen/{id}", HttpMethod.GET, requestEntity2, BaseResp.class, params);
                System.out.println("开奖结果:" + com.alibaba.fastjson.JSONObject.toJSONString(exchange.getBody()));
            }
        }).start();
    }

    private static boolean invite(HttpHeaders authHeaders) {
        HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
        Map<String,Object> params = new HashMap<>();
        params.put("id",aid);
        BaseResp baseResp = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/pigInvitation/invitation/{id}", requestEntity2, BaseResp.class,params);
        if(baseResp.getCode() != null && baseResp.getCode().equals(200)) {
            System.out.println("预约成功");
            return true;
        }
        return false;
    }

    private static RespLogin login(RespVerifyCode respVerifyCode, Integer code) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        ReqLogin reqLogin = new ReqLogin();
        reqLogin.setName("");
        reqLogin.setPassword("");
        reqLogin.setRememberMe(true);
        reqLogin.setVerifyCode(code.toString());
        reqLogin.setVerifyCodeToken(respVerifyCode.getData().getToken());
        HttpEntity<ReqLogin> requestEntity = new HttpEntity<>(reqLogin, requestHeaders);
        RespLogin respLogin = restTemplate.postForObject("http://luck9.luckyzodiac12.com/auth/login", requestEntity, RespLogin.class);
        return respLogin;
    }

    private static RespVerifyCode getCodeUrl() {
        try {
            return restTemplate.getForObject("http://luck9.luckyzodiac12.com/api/verifyCode/get", RespVerifyCode.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //设置APPID/AK/SK
    public static final String APP_ID = "16612736";
    public static final String API_KEY = "LATjbpVShcZSOzNPMockxEs3";
    public static final String SECRET_KEY = "MUweCRHpn2iBzUBvbG0p01XX9zd122jU";
    public static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    public static Integer getCode(String codeUrl) {
        byte[] bytes = getCodeBytes(codeUrl);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        HashMap<String, String> options = new HashMap<>();
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        try {
            JSONObject jsonObject = client.webImage(bytes, options);
            String code = jsonObject.getJSONArray("words_result").getJSONObject(0).getString("words");
            if(code.length() == 4) {
                return Integer.parseInt(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getCodeBytes(String codeUrl) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] bytes = null;
        try {
            bytes = base64Decoder.decodeBuffer(codeUrl);
            FileOutputStream fos = new FileOutputStream("code.jpeg");
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
}
